import 'package:fish_redux/fish_redux.dart';
import 'package:www.znpigai.teacher/global_store/state.dart';

import 'action.dart';
import 'state.dart';

Reducer<PayListState> buildReducer() {
  return asReducer(
    <Object, Reducer<PayListState>>{
      PayListAction.loaded: _loaded,
      PayListAction.loading: _loading,
      PayListAction.listResult: _listResult,
      PayListAction.purchase: _purchase,
      PayListAction.button: _button,
    },
  );
}

PayListState _loading(PayListState state, Action action) {
  return state.clone()..isLoading = true;
}

PayListState _loaded(PayListState state, Action action) {
  return state.clone()..isLoading = false;
}

PayListState _listResult(PayListState state, Action action) {
  final Map<String, dynamic> data = action.payload;
  if (data == null) {
    return state;
  }

  int pageIndex = data['pageIndex'];
  final PayListState newState = state.clone()
    ..pageTotal = data['pageTotal']
    ..pageIndex = pageIndex;

  if (pageIndex == GlobalState.firstPageIndex + 1) {
    newState.items = data['items']; // reset if first page
  } else {
    newState.items.addAll(data['items']);
  }

  return newState;
}

PayListState _purchase(PayListState state, Action action) {
  PayListState params = action.payload;
  return state.clone()
    ..isPurchaseAvailable = params.isPurchaseAvailable
    ..queryProductError = params.queryProductError
    ..products = params.products
    ..purchases = params.purchases
    ..notFoundIds = params.notFoundIds
    ..consumables = params.consumables
    ..purchasePending = params.purchasePending
    ..loadingPurchase = params.loadingPurchase;
}

PayListState _button(PayListState state, Action action) {
  return state.clone()..buttonText = action.payload;
}
